/**
 * Created by aszer on 2016/11/12.
 */
tc = {
    ApiPath: '/dwr/jsonp/',
    format: function (data) {
        var jsonString = JSON.parse(data)['reply'];
        if (!jsonString) {
            tc.e({emessage: "系统错误"});
        }
        var json = JSON.parse(jsonString);
        if (json.hasOwnProperty("etype")) {
            tc.e(json);
            return null;
        } else {
            for (var key in json) {
                if (json.hasOwnProperty(key) && json[key] == null)
                    delete json[key];
            }
            return json;
        }
    },
    e: function (data) {
        if (data['emessage']) alert(data['emessage']);
        if (data['ejump']) window.location.href = data['ejump'];
    },
    findAll: function (service, start, length, cb) {
        $.get(this.ApiPath + service + '/findAll/' + start + '/' + '/' + length, function (data) {
            cb && cb(tc.format(data));
        })
    },
    attach: function (service, obj, cb) {
        $.get(this.ApiPath + service + '/attach/' + JSON.stringify(obj), function (data) {
            cb && cb(tc.format(data));
        })
    },
    delete: function (service, id, cb) {
        $.get(this.ApiPath + service + '/myDelete/' + id, function (data) {
            cb && cb(tc.format(data));
        })
    },
    login: function (name, pw, cb) {
        $.get(this.ApiPath + 'LoginService/login/' + name + '/' + pw, function (data) {
                cb && cb(tc.format(data));
            }
        );
    },
    logout: function (cb) {
        $.get(this.ApiPath + 'LoginService/logout/', function (data) {
                cb && cb(tc.format(data));
            }
        );
    },
    adminLogin: function (name, pw, cb) {
        $.get(this.ApiPath + 'LoginService/adminLogin/' + name + '/' + pw, function (data) {
                cb && cb(tc.format(data));
            }
        );
    },
    adminLogout: function (cb) {
        var self = this;
        $.get(this.ApiPath + 'LoginService/adminLogout/', function (data) {
                cb && cb(tc.format(data));
            }
        );
    }
};
/*
 * 逻辑关系:root>block>template
 * root:整个组件,包括数据项和按钮等
 * block:一定是template的直接父元素,用于存放生成的数据项
 * template:用于生成数据项的模板元素*/
core = {
    stringFormat: function (string, replaceInfo) {
        var values = string.match(/\$[a-zA-Z]+/g);
        var nString = string;
        for (var key in values) {
            if (values.hasOwnProperty(key)) {
                var rKey = values[key].substr(1);
                if (replaceInfo[rKey] === undefined) {
                    console.error('不存在的键:' + rKey);
                    nString = nString.replace(values[key], '');
                } else {
                    //console.log(string,replaceInfo[rKey]);
                    nString = nString.replace(values[key], replaceInfo[rKey]);
                }
            }
        }
        return nString;
    },
    run: function () {
        $('.root').each(function (elem) {
            core.createPage(elem, 0, 20, function (res) {
            });
        })
    },
    createPage: function (root, start, length, cb) {
        var r = $(root);
        var parent = r.find('.block:first');
        var e = parent.find('.template:first');
        var temp = core.getTempHTML(e, false);
        var service = e.get(0).dataset['service'];
        tc.findAll(service, start, length, function (data) {
            for (var key in data) {
                if (data.hasOwnProperty(key)) {
                    data[key]['TData'] = JSON.stringify(data[key]);
                    var html = core.stringFormat(temp, data[key]);
                    $(parent).append(html);
                }
            }
            cb && cb(data);
        })
    },
    getTempHTML: function (e, TRowChange) {
        e.hide();
        e.removeClass('template');
        e.attr('TRowChange', TRowChange);
        e.get(0).dataset.TData = '$TData';
        var temp = elem.outerHTML;
        e.addClass('template');
        return temp;
    },
    add: function (btn) {
        var parent = $(btn).parents('.root:first').find('.block');
        var e = parent.find('.template:first');
        var data = {};
        parent.find('[newRow]').find('input').each(function (elem) {
            var key = e.dataset['service'] + e.dataset.target;
            var value = $(e).val();
            if (!kit.isNorU(value) && value != '') {
                data[key] = value;
            }
        });
        tc.attach(e.dataset['service'], data, function (data) {
            console.log(data);
        });
    },
    delete: function (btn) {
        var parent = $(btn).parents('[TRowChange]:first').get(0);
        var data = JSON.parse(parent.dataset.TData);
        tc.delete(parent.dataset['service'], data['id'], function (res) {

        })
    },
    update: function () {
        $('[TRowChange="true"]').each(function (elem) {
            var update = false;
            var data = JSON.parse(elem.dataset.TData);
            $(elem).find('input').each(function (e) {
                var key = e.dataset['service'] + e.dataset.target;
                var value = $(e).val();
                if (!kit.isNorU(value) && data.hasOwnProperty(key)) {
                    if (data[key] == value) {
                        delete data[key];
                    } else {
                        data[key] = value;
                        update = true;
                    }
                }
            });
            if (update) {
                tc.attach(e.dataset['service'], data, function (data) {
                    console.log(data);
                })
            }
        });
    }
};
selectPage = {
    perPage: 20,
    init: function () {
        this.pageNum = parseInt();
        var e = this.e = $('#select_page').find('ul');
        e.empty();
    },
    select: function (btn, page) {
        this.changePage(page);
        var parent = $(btn).parents('.root:first');
        core.createPage(parent, (page - 1) * selectPage.perPage, (page) * selectPage.perPage);
    },

    changePage: function (page) {
        var start = page - 4;
        var end = page + 4;
        if (start < 1) {
            start = 1
        }
        var e = this.e = $('#select_page').find('ul');
        e.empty();
        if (start !== 1) {
            e.append('<li><a href="javascript:selectPage.select(1)">&lt;&lt;</a></li>');
        }
        for (var i = start; i <= end; i++) {
            e.append('<li id="page' + i + '"><a href="javascript:selectPage.select(' + i + ')">' + i + '</a></li>');
        }
        if (end !== this.pageNum) {
            e.append('<li><a href="javascript:selectPage.select(' + this.pageNum + ')">&gt;&gt;</a></li>');
        }
        e.find('.active').removeClass('active');
        e.find('#page' + page).addClass('active');

    }
};
kit = {
    isNorU: function (arg) {
        return arg === undefined || arg === null;
    },
    pathFmt: function () {
        var res = [];
        for (var key in arguments) {
            if (key == 0) {
                res.push(arguments[0].replace(/\/+$/, ''));
            }/*首个特殊处理*/
            else if (arguments.hasOwnProperty(key)) {
                res.push(arguments[key].replace(/^\/*(.+)\/*$/, '$1'));
            }
        }
        return res.join('/');
    },
    argFmt: function (args) {/*对变量默认值统一管理*/
        for (var key in args) {
            var def;
            if (args.hasOwnProperty(key) &&
                this.isNorU(args[key]) &&
                (!this.isNorU(def = arguments[(parseInt(key) + 1).toString()]))) {
                args[key] = def;
            }
        }
    },
    check: function (string, reg) {
        return string.search(reg) === 0;
    }
};